/**
 * Created by waiwai on 17-7-19.
 */

const multiparty = require('multiparty')
const fs = require('fs')
const moment = require('moment')
const images = require('images')
const path = require('path')

const uploadPath = 'public/upload/'
function createDir(newPath, cb) {
  fs.access(newPath, (err) => {
    if (err) { // 不存在目录
      fs.mkdir(newPath, '0777', (suberr) => {
        cb && cb(suberr)
      })
    } else {
      cb && cb()
    }
  })
}
function imgProcess(req, cb) {
  const form = new multiparty.Form({
    encoding: 'utf-8',
    uploadDir: uploadPath,
    maxFilesSize: 5 * 1024 * 1024, // 5M
  })
  form.parse(req, (err, fields, files) => {
    if (err) {
      console.error(err)
      req.flash('error', '文件不符合要求')
      return cb && cb(err)
    }
    const obj = {}
    Object.keys(fields).forEach((name) => { // 文本
      obj[name] = fields[name]
    })
    let file = []
    Object.keys(files).forEach((name) => { // 文件
      file = files[name]
    })
    const now = moment().format('YYYYMMDD')
    // let newPath=uploadPath+now+"/";
    const newPath = path.join(uploadPath, `${now}/`)
    createDir(newPath, () => {
      const imgfiles = []
      file.forEach((ctx) => {
        console.log(ctx.path)
        const img = images(ctx.path)
        const imgType = ctx.path.match(/\.\w+$/ig)[0]
        const imgName = ctx.path.replace(path.join(uploadPath), '').replace(imgType, '')
        const fullName = `${imgName}_$date${now}_$${img.width()}x${img.height()}${imgType}`

        const pushObj = {
          name: fullName,
          width: img.width(),
          height: img.height(),
          type: ctx.headers['content-type'],
          url: (newPath + fullName).replace('public', '').replace(/\\/g, '/'),
        }
        const small = true
        if (small) {
          const smallImg = images(img).resize(220)
          const smallName = `${fullName.replace(imgType, '')}_$sma_${smallImg.width()}x${smallImg.height()}${imgType}`
          smallImg.save(newPath + smallName, { quality: 60 })
          pushObj.thumb = {
            name: smallName,
            url: (newPath + smallName).replace('public', '').replace(/\\/g, '/'),
            width: smallImg.width(),
            height: smallImg.height(),
          }
        }
        img.save(newPath + fullName)
        imgfiles.push(pushObj)
        fs.unlink(ctx.path, (err) => {
          if (err) {
            console.error(err)
          }
        })
      })
      cb && cb(null, obj, imgfiles)
    })
  })
}
module.exports = imgProcess
